package com.umeox.moto.watch.fitness.receiver;


import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;

import com.umeox.moto.common.log.Logger;
import com.umeox.moto.common.utils.DateUtils;
import com.umeox.moto.watch.fitness.BuildConfig;
import com.umeox.moto.watch.fitness.bean.SportChallengeDetail;
import com.umeox.moto.watch.fitness.ui.ChallengeTipActivity;
import com.umeox.moto.watch.fitness.utils.Utils;

import java.util.List;


public class AlarmReceiver extends BroadcastReceiver {
    private static final String TAG = AlarmReceiver.class.getSimpleName();
    public static final String ACTION_ALARM_BELL = "com.umeox.moto.intent.action.ACTION_ALARM_BELL";
    public static final String ACTION_UPDATED_ALARMLIST = "com.umeox.moto.intent.action.UPDATE_ALARM_LIST";
    public static final String ACTION_CANCEL_ALARM = "com.umeox.moto.intent.action.CANCEL_ALARM";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action == null || TextUtils.isEmpty(action)) {
            return;
        }

        if (action.equals(ACTION_UPDATED_ALARMLIST)) {
            Logger.w("运动挑战闹钟列表更新，先取消设置的运动挑战闹钟，然后重新计算");
            cancelAlarm(context);
            List<SportChallengeDetail> alarmDataList = Utils.getSportChallengeList( );
            //获取下次闹钟时间，并且计算重复闹钟下次响铃时间
            SportChallengeDetail nextAlarm = Utils.getNextSportChallengeDetail(alarmDataList);
            if (nextAlarm != null) {
                setAlarm(context, nextAlarm);
            } else {
                Logger.w("当前没有可用闹钟");
                cancelAlarm(context);
            }
        } else if (action.equals(ACTION_CANCEL_ALARM)) {
            //解绑后会发送这个广播，通知取消所有已经设置的闹钟
            cancelAlarm(context);
        }
    }

    @SuppressLint("WrongConstant")
    private void setAlarm(Context context, final SportChallengeDetail detail) {
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (am == null) {
            Logger.e("The service named alarm does not exist.");
            return;
        }
        Intent intent = new Intent();
        PendingIntent pdIntent;
        if (BuildConfig.FLAVOR.equals("Kid_Phone")) {
            Bundle mBundle = new Bundle();
            mBundle.putLong(Utils.EXTRA_KEY_ID, detail.id);
            mBundle.putBoolean(Utils.EXTRA_KEY_AUTO, true);
            intent.putExtras(mBundle);
            intent.setClass(context, ChallengeTipActivity.class);
            pdIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        } else {
            intent.setAction(ACTION_ALARM_BELL);
            Bundle mBundle = new Bundle();
            mBundle.putLong(Utils.EXTRA_KEY_ID, detail.id);
            mBundle.putBoolean(Utils.EXTRA_KEY_AUTO, true);
            intent.putExtras(mBundle);
            pdIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }


        long currentTime = System.currentTimeMillis();
        Logger.w("当前时间:" + DateUtils.formatDateTime(currentTime));
        Logger.w("运动挑战时间:" + DateUtils.formatDateTime(detail.alarmTimeInMillis));
        //set方法4.4以后已经不能精确到设置的时间，改用setExact方法设置闹钟
        long time = detail.alarmTimeInMillis;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time, pdIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            am.setExact(AlarmManager.RTC_WAKEUP, time, pdIntent);
        } else {
            am.set(AlarmManager.RTC_WAKEUP, time, pdIntent);
        }
    }

    /**
     * 1.   Intent中的setData使用的值，必须和cancel中intent里面setData用的值一样，否则点击cancel是没法取消掉的，
     * 或者你不setData，那也是没法取消的
     * 2.   Intent中的setClass使用的值也必须和cancel众intent使用的一样，不然也cancel不掉，不setClass也cancel不了
     * 3.   Intent中的putExtra是无效的，根本不起区别的作用
     * 4.   getBroadcast的第二个参数，一般的ap都是写0,其实假如你前面的intent只有setAction过，
     * 那么单纯用reqeustCode也是可以区别不同的alarm的。
     * 5.   通常cancel之前可以先用PendingIntent.FLAG_NO_CREATE来判断之前是不是设定了这个alarm，
     * 假如没设定，那就不要去调用cancel
     */
    private void cancelAlarm(Context context) {
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent();
        intent.setAction(ACTION_ALARM_BELL);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_NO_CREATE);
        if (sender != null) {
            log("取消已经设置的运动挑战闹钟");
            am.cancel(sender);
        } else {
            log("当前没有设置运动挑战闹钟，不用取消");
        }
    }

    private void log(String text) {
        Logger.d(TAG, text);
    }
}
